// ==UserScript==
// @name         【bbs.tampermonkey.net.cn】阿里云盘脚本V1.4
// @namespace    http://tampermonkey.net/
// @version      1.4
// @description  try to take over the world!
// @author       李恒道
// @match        https://passport.aliyundrive.com/*
// @match        https://www.aliyundrive.com/drive/*
// @match        https://www.aliyundrive.com/drive
// @match        https://aliyundrive.com/drive/*
// @match        https://aliyundrive.com/drive
// @icon         https://www.google.com/s2/favicons?domain=aliyundrive.com
// @require      https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js
// @grant        unsafeWindow
// @grant        GM_setClipboard
// @grant        GM_xmlhttpRequest
// @supportURL   https://bbs.tampermonkey.net.cn/forum.php?mod=viewthread&tid=427
// @homepage     https://bbs.tampermonkey.net.cn/forum.php?mod=viewthread&tid=427
// @supportURL   https://bbs.tampermonkey.net.cn/forum.php?mod=viewthread&tid=427
// @homepage     https://bbs.tampermonkey.net.cn/forum.php?mod=viewthread&tid=427
// @supportURL   https://bbs.tampermonkey.net.cn/forum.php?mod=viewthread&tid=427
// @homepage     https://bbs.tampermonkey.net.cn/forum.php?mod=viewthread&tid=427
// ==/UserScript==

let username=''
let password=''
//自动登陆配置项

let FileList=[]
let CreateListner=false;
let listurl=''
let CreateSaveBtn=false;
var ShowFileObj={
    name:'文件获取失败',
    content_hash:'hash获取失败',
    size:'公众号:叛逆青年旅舍，来自油猴中文网:bbs.tampermonkey.net.cn',
    content_type:'Fucccccck',
    file_id:'天才少年李恒道',
    content_type:'系统李恒道吹牛逼理论，QQ4548212'
}
let accesstoken=''
function ShowToast(text,time=3000){
    let toast=document.createElement('div')
    toast.innerHTML='<div><div class="drive-toast"><div><div class="drive-toast-notice"><div class="drive-toast-notice-content"><div class="drive-toast-custom-content drive-toast-info"><div></div><span><div class="content-wrapper--B7mAG" style="margin-left: 20px; " data-desc="false"><div class="title-wrapper--3bQQ2">'
        + text+
        '<div class="desc-wrapper--218x0"></div></div></div></span></div></div></div></div></div></div>'
    document.querySelector('body').append(toast)
    setInterval(function(){toast.remove() }, time);

}
function RefreshToken(){
    if(accesstoken!=='')
    {
        return;
    }

    console.log('refresh_token！',JSON.parse(localStorage.getItem('token')).refresh_token);
    GM_xmlhttpRequest({
        url:"https://websv.aliyundrive.com/token/refresh",
        method :"POST",
        data:'{"refresh_token": "'+JSON.parse(localStorage.getItem('token')).refresh_token+'"}',
        headers: {
            "Content-type": "application/json;charset=utf-8",
        },
        onload:function(xhr){
            var json = JSON.parse(xhr.responseText);
            accesstoken=json.access_token
            if(accesstoken!==undefined&&accesstoken!='')
            {

            }
            else{
                ShowToast('解析Acess_Token失败!')

            }
        }
    });
}
function CreateShareClip(tempobj){
    ShowFileObj.name=tempobj.name;
    ShowFileObj.content_hash=tempobj.content_hash;
    ShowFileObj.size=tempobj.size;
    ShowFileObj.content_type=tempobj.content_type;
    ShowFileObj.file_id=tempobj.file_id;
    ShowFileObj.content_type=tempobj.content_type;
    console.log('ShowFileObj',ShowFileObj)
    let ret=confirm('文件名:'+ShowFileObj.name+'\n校验值:'+ShowFileObj.content_hash+'\n文件大小:'+ShowFileObj.size+'\n'+
                    '点击确定自动添加分享码到剪辑版\n来自油猴中文网bbs.tampermonkey.net.cn\n公众号:叛逆青年旅舍');
    if(ret==true)
    {
        console.log('设置剪辑版',JSON.stringify(ShowFileObj))
        try
        {
            GM_setClipboard(window.btoa(unescape(encodeURIComponent(JSON.stringify(ShowFileObj)))))
            alert('文件已设置到剪辑版！')
        }
        catch(err)
        {
            console.log('文件名字可能存在特殊关键字，请改名重试',err)

            alert('文件名字可能存在特殊关键字，请改名重试')
        }

    }
}
function StartListner(){

    let bodyel=document.querySelector('body');
    console.log('StartListner',bodyel)
    bodyel.addEventListener("DOMNodeInserted", function(event) {
        if(CreateSaveBtn===false)
        {
            let header=document.querySelector('[class|=header]')
            if(header!==null&&header.childElementCount===2&&document.querySelector('[class|=header]').children[1].innerText.indexOf('提取分享码')===-1){
                let GenerateShareBtn=document.createElement('div')
                GenerateShareBtn.innerHTML='<div class="button-wrapper--1UkG6" data-type="primary" data-spm-anchor-id="0.0.0.i3.35676c7515rlzj" style="margin-left: 15px;">提取分享码</div>'
                GenerateShareBtn.onclick=function(){
                    var text=prompt("请输入分享码","");
                    text=decodeURIComponent(escape(window.atob(text)))
                    text=JSON.parse(text)
                    if(text.content_hash==undefined)
                    {
                        alert('提取码不正确！')
                    }
                    else{
                        let useruid=JSON.parse(localStorage.getItem('token')).default_drive_id
                        let uploadtext='{"drive_id":"'+useruid+'","part_info_list":[{"part_number":1}],"parent_file_id":"root","name":"'+text.name+'","type":"file","check_name_mode":"auto_rename","size":'+text.size+',"content_hash":"'+text.content_hash+'","content_hash_name":"sha1"}'
                        console.log('上传文本',uploadtext)

                        GM_xmlhttpRequest({
                            url:"https://api.aliyundrive.com/v2/file/create",
                            method :"POST",
                            data:uploadtext,
                            headers: {
                                "Content-type": "application/json;charset=utf-8",
                                "Authorization": accesstoken
                            },
                            onload:function(xhr){
                                var json = JSON.parse(xhr.responseText);
                                console.log('获取成功！',json);
                                if(json.rapid_upload==true)
                                {
                                    alert("提取文件成功！")
                                    unsafeWindow.location.reload();
                                }
                                else{
                                    alert("提取文件失败！")
                                }
                            }
                        });

                    }

                }
                document.querySelector('[class|=header]').children[1].append(GenerateShareBtn)
            }

        }

        if(event.relatedNode.innerHTML.indexOf('详细信息')!=-1)
        {
            console.log('创建分享码',event.relatedNode.innerHTML)
            if(event.relatedNode.innerHTML.indexOf('创建时间')!=-1)
            {
                if(document.querySelector('.ant-modal-body img').alt==="folder")
                {
                    if(document.querySelector('.ant-modal-body').innerText.indexOf('生成分享')!==-1)
                    {
                        document.querySelector('.ant-modal-body [data-type="primary"]').remove()
                    }
                    return;

                }


                if(event.relatedNode.innerHTML.indexOf('生成分享')==-1)
                {
                    let GenerateFileDate=document.createElement('div')
                    GenerateFileDate.innerHTML='<div class="button-wrapper--1UkG6" data-type="primary">生成分享</div>'
                    GenerateFileDate.onclick=function(){
                        let name=document.querySelector('[class|=title-wrapper]').innerText
                        for(let index=0;index<FileList.length;index++){
                            let templist=FileList[index]
                            for(let innerindex=0;innerindex<templist.list.length;innerindex++)
                            {
                                console.log('列表循环',templist)
                                let tempobj=templist.list[innerindex]

                                if(tempobj.type!=='folder')
                                {
                                    if(tempobj.name===name)
                                    {
                                        console.log('找到了对象',tempobj)
                                        CreateShareClip(tempobj)
                                    }

                                }

                            }

                        }
                    }
                    let WrapperList=document.querySelectorAll('[class*=group-wrapper]')
                    WrapperList[WrapperList.length-1].append(GenerateFileDate)

                }




            }


        }
    });
}
if(unsafeWindow.location.href.indexOf('aliyundrive.com/drive')!=-1)
{
    unsafeWindow.fetch=''
    function addXMLRequestCallback(callback){
        var oldSend, i;
        if( XMLHttpRequest.callbacks ) {
            XMLHttpRequest.callbacks.push( callback );
        } else {
            XMLHttpRequest.callbacks = [callback];
            oldSend = XMLHttpRequest.prototype.send;
            XMLHttpRequest.prototype.send = function(){
                for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
                    XMLHttpRequest.callbacks[i]( this );
                }
                oldSend.apply(this, arguments);
            }
        }
    }
    addXMLRequestCallback( function( xhr ) {
        xhr.addEventListener("load", function(){
            if ( xhr.readyState == 4 && xhr.status == 200 ) {
                if(xhr.responseURL==="https://api.aliyundrive.com/v2/file/list")
                {
                    let quit=false;
                    document.querySelectorAll('.ant-modal-header').forEach((item)=>{
                        if(item.innerText.indexOf('移动')!==-1)
                        {
                            if(item.offsetWidth!==0)
                            {
                                quit=true
                            }

                        }
                    })
                    if(quit)
                    {
                        return;
                    }

                    if(listurl===unsafeWindow.location.href)
                    {
                        let Search=false;
                        FileList.forEach((item)=>{
                            if(item.name===JSON.parse(xhr.response).next_marker)
                            {
                                item.list=JSON.parse(xhr.response).items
                                Search=true
                            }
                        })
                        if(Search===false)
                        {
                            FileList=[...FileList,{name:JSON.parse(xhr.response).next_marker,list:JSON.parse(xhr.response).items}]
                        }
                    }
                    else{
                        listurl=unsafeWindow.location.href
                        FileList=[{name:JSON.parse(xhr.response).next_marker,list:JSON.parse(xhr.response).items}]
                    }

                    let filenum=0;
                    for(let index=0;index<FileList.length;index++){
                        filenum+=FileList[index].list.length
                    }
                    if(CreateListner===false)
                    {
                        StartListner()
                        CreateListner=true
                    }
                    RefreshToken()
                    console.log('获取FileList数据')
                    ShowToast('已获取文件列表 数量为'+filenum+'(删除文件可能对其数字不准) By:天才少年李恒道')

                }
            }
        });

    });

}

if(unsafeWindow.location.href.indexOf('passport.aliyundrive.com/mini_login.htm')!=-1)
{
    let container=document.querySelector('#container');

    container.addEventListener("DOMNodeInserted", function(event) {
        if(username=='')
        {
        return}
                if(password=='')
        {
        return}

        let header=document.querySelector('.login-blocks')
        console.log('header',header)
        if(header===null)
        {
            return;
        }
        document.querySelector('.login-blocks').children[1].click()
        document.querySelector('#fm-login-id').value=username
        document.querySelector('#fm-login-password').value=password
        document.querySelector('.password-login').click()

    });



    return;
}




